package com.linkai.onlinetool.service;

import com.aliyun.ocr.Client;
import com.aliyun.ocr.models.Config;
import com.aliyun.ocr.models.RecognizeCharacterAdvanceRequest;
import com.aliyun.ocr.models.RecognizeCharacterResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;

@Service
public class AIService {

    private Client ocrClient;
    private RuntimeOptions runtimeOptions;

    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${accessKeySecret}")
    private String accessKeySecret;

    @PostConstruct
    private void init() throws Exception {
        Config config = new Config();

        config.type = "access_key";
        config.regionId = "cn-shanghai";
        config.accessKeyId = accessKeyId;
        config.accessKeySecret = accessKeySecret;
        config.endpoint = "ocr.cn-shanghai.aliyuncs.com";

        ocrClient = new Client(config);
        runtimeOptions = new RuntimeOptions();
    }


    public String myRecognizeCharacter(InputStream is) throws Exception {
        RecognizeCharacterAdvanceRequest request = new RecognizeCharacterAdvanceRequest();
        request.imageURLObject = is;
        request.minHeight = 10;
        request.outputProbability = true;

        RecognizeCharacterResponse response = ocrClient.recognizeCharacterAdvance(request, runtimeOptions);

        StringBuffer result = new StringBuffer();
        for (RecognizeCharacterResponse.RecognizeCharacterResponseDataResults item:response.data.results
             ) {
            result.append(item.text + "\n");
        }

        return result.toString();
    }

    public String uploadImage(MultipartFile file, HttpServletRequest request) {
        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();
        System.out.println("上传文件名 : "+uploadFileName);

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println(uuid);
        String newFileName = "AI-Word-" + uuid + "-" + uploadFileName;

        //上传路径保存设置   UUID
        String path = request.getServletContext().getRealPath("/upload");
//        String path = "src/main/resources/static/upload";
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址："+realPath);

        InputStream is = null; //文件输入流
        OutputStream os = null;
        try {
            is = file.getInputStream();
            os = new FileOutputStream(new File(realPath, newFileName)); //文件输出流

            //读取写出
            int len=0;
            byte[] buffer = new byte[1024];
            while ((len=is.read(buffer))!=-1){
                os.write(buffer,0,len);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 返回该图片的路径
        return realPath + "\\" + newFileName;
    }

}
